package net.tngou.db.manage;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.SortField;

import net.tngou.db.entity.Field;
import net.tngou.db.entity.Limit;
import net.tngou.db.entity.Page;
import net.tngou.db.i18n.I18N;
import net.tngou.db.util.ResultSet;


/**
 * 
 *   数据查询语言（DQL）
        从数据库中的一个或多个表中查询数据(SELECT)
 * @author tngou
 *
 */
public class DQL extends SQL{

	
	@SuppressWarnings("unchecked")
	public ResultSet select() {
		Page page=null;
		List<String> tables = (List<String>) request.getParameter("tables");  //表
		
		if(tables.size()==1)
		{
			response=getCache(request, tables.get(0));
			if(response!=null)return response;
		}
		response = new ResultSet();

		String[] tablesNames = null;
		if(!tables.isEmpty()){
			tablesNames=(String[]) tables.toArray(new String[tables.size()]);
		}
		List<Field> wheres  = (List<Field>) request.getParameter("wheres"); //条件
		Limit limit = (Limit) request.getParameter("limit");                 //大小
//		List<String> items=(List<String>) request.getParameter("items");     //字段
		List<SortField> sortFields = (List<SortField>) request.getParameter("sortFields"); //排序
		SortField[] sorts =null;
		if(!sortFields.isEmpty()){
			sorts=(SortField[]) sortFields.toArray(new SortField[sortFields.size()]);
		}
		if(wheres.isEmpty())
		{
			boolean reverse=true;
			page = luceneManage.get(limit.getStart(), limit.getSize(), reverse, tables.get(0));	
			
		}else
		{
			if(wheres.size()==1)
			{
				Field field = wheres.get(0);

				
				page = luceneManage.get(limit.getStart(), limit.getSize(), field, sorts, tablesNames);
			}else
			{
				Field[] fields =(Field[]) wheres.toArray(new Field[wheres.size()]);
				Occur[] flags=new Occur[fields.length];
				for (int i = 0; i < fields.length; i++) {
					Field field = fields[i];
					switch (field.getType()) {
					case Text:
						flags[i]=BooleanClause.Occur.SHOULD;
						break;
	                 case String:
	                	 flags[i]=BooleanClause.Occur.MUST;
						break;
					default:
						flags[i]=BooleanClause.Occur.MUST;
						break;
					}
					
				}
				page = luceneManage.get(limit.getStart(), limit.getSize(), fields ,flags, sorts, tablesNames);
			}
			
		}
		
		

			try {
				BeanUtils.copyProperties(response, page);
				
			} catch (IllegalAccessException | InvocationTargetException e) {
				
//				e.printStackTrace();
			}
		if(response!=null&&response.getList()!=null)	
		response.setMsg(I18N.getValue("select",response.getTotal()+"",response.getList().size()+""));
		
		if(tables.size()==1)setCache(request, response, tables.get(0)); //添加缓存
		
		return response;
	}
}
